
export default class Request{
	constructor(domain, tokenUrl='login', code='code', method='POST', tokenPrefix='Bearer ') {
		if(!domain.startsWith('https://')){
			domain='https://' + domain
		}
		if(domain.startsWith('http://')){
			domain=domain.replace('http://', 'https://')
		}
		if(!domain.endsWith('/')){
			domain = domain + '/'
		}
		if(tokenUrl.startsWith('./')){
			tokenUrl = tokenUrl.replace('./', '')
		}
	    this.domain = domain
		this.tokenUrl = tokenUrl
		this.token=''
		this.code=code
		this.method=method
		this.tokenPrefix = tokenPrefix
	}
	async request(url='', data={}, method='GET', dataType='json'){
		return new Promise((reject, resolve)=>{
			uni.checkSession({
				success: () => {
					this.token=uni.getStorageSync('token')
					// 请求
					uni.request({
						method,
						url:this.domain + url,
						data,
						dataType,
						header:{
							Authorization: this.tokenPrefix + this.token,
						},
						fail: (err) => {
							console.error(err)
							reject(err)
						},
						success: (res) => {
							const {data} = res
							resolve(data)
						}
					})
				},
				fail: () => {
					uni.login({
						success: (res) => {
							if(res.code){
								uni.request({
									url:this.domain + this.tokenUrl,
									method: this.method,
									data:{
										[this.code]: res.code,
									},
									success: (res) => {
										const {data} = res
										const token = data.data
										// 请求
										uni.request({
											method,
											url:this.domain + url,
											data,
											dataType,
											header:{
												Authorization: this.tokenPrefix + this.token,
											},
											fail: (err) => {
												console.error(err)
												reject(err)
											},
											success: (res) => {
												const {data} = res
												resolve(data)
											}
										})
										uni.setStorageSync('token', token)
										this.token=token
									},
									fail: (err) => {
										console.error(err)
										reject(err)
									}
								})
							}
						}
					})
				},
				complete: () => {
					getApp().globalData.token=this.token
				}
			})
		})
	}
	async get(url='', data={}, dataType='json'){
		return this.request(url, data, 'GET', dataType)
	}
	async post(url='', type='json', data={}){
		return this.request(url, data, 'POST', dataType)
	}
	async del(){
		return this.request(url, data, 'DELETE', dataType)
	}
	async put(){
		return this.request(url, data, 'PUT', dataType)
	}
	async patch(){
		return this.request(url, data, 'PATTCH', dataType)
	}
}